<template>
  <!--  <el-form ref="form2" size="small" :model="form2" label-width="135">
    <el-form-item label="属性选择">
      <el-checkbox-button
        v-for="item in propList"
        :key="item.id"
        v-model="item.checked"
        :label="item.id"
      >{{ item.spec_kind_name }}</el-checkbox-button>
    </el-form-item>
    <el-form-item label="规格选择（可多选）:" style="white-space: nowrap">
      <el-form-item
        v-for="item in propList"
        v-if="item.checked"
        :key="item.id"
        :label="item.spec_kind_name"
      >
        <el-checkbox-group v-model="spec[item.id]">
          <el-checkbox
            v-for="spec in item.spec"
            :key="spec.id"
            :label="spec.id"
            @change="$forceUpdate()"
          >{{ spec.spec_name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form-item>
  </el-form>-->
  <div>
    <el-form ref="form" :rules="rules" :model="form" label-width="150px">
      <el-form-item label="规格选择(可多选):">
        <el-button
          v-for="(item, index) of list"
          :key="item.id"
          :class="{'active': isActive.includes(index)}"
          @click="handleButtonClick(index)"
        >{{ item.spec_kind_name }}</el-button>
      </el-form-item>
      <div v-if="isActive.length" class="property-choose">
        <div class="property-label">可选值:</div>
        <div class="content-wrapper">
          <div
            v-for="(item, index) of list"
            v-show="isActive.includes(index)"
            :key="item.id"
            class="prop-wrapper"
          >
            <el-form-item class="check" :label="item.spec_kind_name + ':'" prop="checkList">
              <el-checkbox-group v-model="form.checkList" @change="handleCheckedChange">
                <el-checkbox
                  v-for="secItem in item.spec"
                  :key="secItem.id"
                  :label="secItem.id"
                >{{ secItem.spec_name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>
        </div>
      </div>
      <div v-if="isActive.length && form.checkList.length" class="specifications-wrapper">
        <div class="specifications-label">规格价格:</div>
        <div class="specifications-content">
          <el-table :data="tableData" style="width: 100%" border>
            <el-table-column label="图片" width="100">
              <template slot-scope="scope">
                <div class="pic-upload">
                  <my-upload
                    :img="scope.row.spec_img"
                    class="myUpload"
                    :width="80"
                    :height="80"
                    @click="hanldeMyUploadClick(scope.$index)"
                    @success="handleSuccess"
                  />
                </div>
              </template>
            </el-table-column>
            <template v-for="(item, index) in propArr">
              <el-table-column :label="item">
                <template slot-scope="scope">
                  <div>{{ scope.row.prop[index] }}</div>
                </template>
              </el-table-column>
            </template>
            <el-table-column label="成本价" width="150">
              <template slot-scope="scope">
                <div>
                  <el-input-number
                    v-model="scope.row.cost"
                    size="mini"
                    controls-position="right"
                    :min="1"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="原价" width="150">
              <template slot-scope="scope">
                <div>
                  <el-input-number
                    v-model="scope.row.original_price"
                    size="mini"
                    controls-position="right"
                    :min="1"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="现价" width="150">
              <template slot-scope="scope">
                <div>
                  <el-input-number
                    v-model="scope.row.spe_price"
                    size="mini"
                    controls-position="right"
                    :min="1"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="vip价" width="150">
              <template slot-scope="scope">
                <div>
                  <el-input-number
                    v-model="scope.row.discount_price"
                    size="mini"
                    controls-position="right"
                    :min="1"
                    :disabled="vipDisable"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="积分" width="150" v-if="tableData.length && tableData[0].hasOwnProperty('points') && parseInt(tableData[0].points) > 0">
              <template slot-scope="scope">
                <div>
                  <el-input-number
                    v-model="scope.row.points"
                    size="mini"
                    controls-position="right"
                    :min="1"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="库存" width="150">
              <template slot-scope="scope">
                <div>
                  <el-input-number
                    v-model="scope.row.spec_inventory"
                    size="mini"
                    controls-position="right"
                    :min="1"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <el-form-item label="总库存:" style="margin-top:10px">
        <el-input v-model="calcuInventory" disabled style="width:150px;">
          <template slot="append">件</template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import { editGoodGetParamsTwo, editGoodTwo } from '@/api/good-mng'
import MyUpload from '@/views/add-editor/component/my-upload'
import {
  getSpecificationList,
  priceSpecification,
  saveStepTwo
} from '@/api/good-mng'
const ERR_OK = 200
export default {
  components: {
    MyUpload
  },
  props: {
    id: {
      type: [Number, String],
      default: ''
    },
    propData: {
      type: Object,
      default: () => {}
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      /* propList: [],
      form2: {},
      propId: [],
      spec: {} */
      isActive: [],
      form: {
        inventory: 0,
        checkList: []
      },
      tableData: [],
      ruleForm: {
        id: '',
        spec: []
      },
      list: [],
      data: {},
      propArr: [],
      myUploadIndex: '',
      rules: {
        checkList: [
          {
            type: 'array',
            required: true,
            message: '请选择属性可选值',
            trigger: 'checked'
          }
        ]
      }
    }
  },
  computed: {
    vipDisable() {
      const disable = JSON.parse(localStorage.getItem('vip_rule')) === 0
      return disable
    },
    calcuInventory() {
      let count = 0
      if (this.isActive.length && this.form.checkList.length) {
        this.tableData.forEach((item, index) => {
          count += item.spec_inventory
        })
      } else {
        count = 0
      }
      return count
    }
  },
  watch: {
    propData(newVal) {
      this.ruleForm.id = newVal.commodity.id
      this._getSpecificationList(newVal.commodity.id)
        .then(() => {
          this.setActive(newVal)
          this.tableData = this.formatNewVal(newVal)
          // this.tableData.points =
          let checkList
          if (Array.isArray(newVal.commodity.optionalValueIdArr)) {
            checkList = newVal.commodity.optionalValueIdArr.flat()
            checkList.forEach((item, index) => {
              checkList[index] = parseInt(item)
            })
            this.form.checkList = checkList
            this.ruleForm.spec = this.findSpecificationById(
              this.form.checkList
            )
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  },
  mounted() {
    this._getSpecificationList(this.id)
  },
  created() {
    /*  editGoodGetParamsTwo({ id: this.id }).then(res => {
      if (res.code === 200) {
        this.propList = res.data.map(item => {
          this.spec[item.id] = []
          item.checked = false
          return item
        })
      }
    }) */
  },
  methods: {
    /*  submit() {
      const obj = {}
      for (const i in this.propList) {
        if (this.propList[i].checked) {
          if (!this.spec[this.propList[i].id].length) {
            this.$message({
              message: '请选择规格',
              type: 'warning'
            })
            return
          }
          obj[this.propList[i].id] = this.spec[this.propList[i].id].join(',')
        }
      }
      if (!Object.keys(obj).length) {
        this.$message({
          message: '请选择属性及规格',
          type: 'warning'
        })
        return
      }
      editGoodTwo({
        id: this.id,
        spec: obj
      }).then(res => {
        if (res.code === 200) {
          this.$store.dispatch('goodMng/setSpec', res.data)
          this.$emit('nextStep')
        }
      })
    } */
    setActive(val) {
      if (Array.isArray(val.commodity.attrValueIdArr)) {
        for (let i = 0; i < val.commodity.attrValueIdArr.length; i++) {
          const temp = val.commodity.attrValueIdArr[i]
          for (let j = 0; j < this.list.length; j++) {
            if (
              parseInt(temp) === parseInt(this.list[j].id) &&
              !this.isActive.includes(j)
            ) {
              this.isActive.push(j)
            }
          }
        }
      }
    },
    submit() {
      const params = Object.assign(
        {},
        {
          id: this.ruleForm.id,
          spec_id: this.ruleForm.spec,
          spec: this.tableData
        }
      )
      if (!this.isActive.length) {
        this.$message({
          type: 'warning',
          message: '请选择规格',
          showClose: true
        })
        return
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          this._saveStepTwo(params)
            .then(res => {
              this.$emit('nextStep', res.data.id)
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    hanldeMyUploadClick(index) {
      this.myUploadIndex = index
    },
    handleSuccess(url) {
      this.imgUrl = url
      if (this.myUploadIndex) {
        this.tableData[this.myUploadIndex].spec_img = url
      }
    },
    handleButtonClick(index) {
      if (this.isActive.includes(index)) {
        this.isActive = this.isActive.filter(item => {
          return item !== index
        })
      } else {
        this.isActive.push(index)
      }
    },
    handleCheckedChange(val) {
      this.ruleForm.spec = this.findSpecificationById(val)
      this.ruleForm.id = this.id
      this._priceSpecification(this.ruleForm)
    },
    findSpecificationById(arr) {
      // console.log(arr, 'sdfsdfdf')
      // console.log(this.list, 'list')
      const obj = {}
      for (let i = 0; i < this.list.length; i++) {
        const temp = []
        const item = this.list[i].spec
        temp.push(this.list[i].id)
        if (item) {
          for (let j = 0; j < arr.length; j++) {
            for (let k = 0; k < item.length; k++) {
              if (parseInt(arr[j]) === parseInt(item[k].id)) {
                temp.push(arr[j])
              }
            }
          }
        }
        if (temp.length > 1) {
          obj[temp[0]] = temp.slice(1).join(',')
        }
      }
      return obj
    },
    handleProp(propTemp) {
      const propArr = []
      //  倒序
      this.isActive.sort((a, b) => {
        return b - a
      })
      for (let k = 0; k < propTemp.length; k++) {
        for (let i = 0; i < this.list.length; i++) {
          const obj = this.list[i]
          if (obj.spec) {
            for (let j = 0; j < obj.spec.length; j++) {
              const item = obj.spec[j]
              if (item.spec_name === propTemp[k]) {
                propArr.push(obj.spec_kind_name)
                break
              }
            }
          }
        }
      }
      return propArr
    },
    formatNewVal(newVal) {
      const tableData = []
      let propTemp
      if (Array.isArray(newVal.spec) && newVal.spec.length) {
        newVal.spec.forEach((item, index) => {
          propTemp = item.spec_name.split(',')
          tableData.push({
            prop: propTemp,
            spec_ids: item.spec_ids,
            spec_img: item.spec_img,
            cost: item.cost,
            original_price: item.original_price,
            spe_price: item.spe_price,
            discount_price: item.discount_price,
            spec_inventory: item.spec_inventory,
            points: item.points
          })
        })
        this.propArr = this.handleProp(propTemp)
      }
      return tableData
    },
    formatData(data) {
      const tableData = []
      let propTemp
      data.spec.forEach((item, index) => {
        propTemp = item[0].split(' ')
        tableData.push({
          prop: propTemp,
          spec_ids: item[1],
          spec_img: data.commodity.img_show,
          cost: data.commodity.cost,
          original_price: data.commodity.original_price,
          spe_price: data.commodity.price,
          discount_price: data.commodity.discount_price,
          spec_inventory: data.commodity.inventory,
          points: data.commodity.points
        })
      })
      console.log(tableData, '------')
      this.propArr = this.handleProp(propTemp)
      return tableData
    },
    _getSpecificationList(id) {
      return new Promise((resolve, reject) => {
        getSpecificationList(id)
          .then(res => {
            if (res.code === ERR_OK) {
              console.log(res.data, '&&&&&&&')
              this.list = res.data
              resolve()
            }
          })
          .catch(err => {
            console.log(err)
            reject()
          })
      })
    },
    _priceSpecification({ id, spec }) {
      priceSpecification({ id, spec })
        .then(res => {
          if (res.code === ERR_OK) {
            console.log(res)
            this.data = res.data
            this.tableData = this.formatData(res.data)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    _saveStepTwo({ id, spec_id, spec }) {
      return new Promise((resolve, reject) => {
        saveStepTwo({ id, spec_id, spec })
          .then(res => {
            if (res.code === ERR_OK) {
              console.log(res)
              this._success(res)
              resolve(res)
            }
          })
          .catch(err => {
            console.log(err)
            reject(err)
          })
      })
    },
    _success(res) {
      this.$message({
        type: 'success',
        message: res.message,
        showClose: true
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.active {
  background: #409eff;
  color: #fff;
}
.property-choose {
  display: flex;
  .property-label {
    font-family: Roboto;
    width: 150px;
    height: 40px;
    text-align: right;
    padding-right: 12px;
    margin-top: 8px;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    font-weight: 700;
  }
  .content-wrapper {
    width: 970px;
    padding-top: 20px;
    box-sizing: border-box;
    border-radius: 6px;
    // background-color: rgba(250, 250, 250, 1);
    // border: 1px solid rgba(255, 0, 0, 0);
  }
}
.specifications-wrapper {
  display: flex;
  margin-top: 20px;
  .specifications-label {
    width: 150px;
    font-family: Roboto;
    height: 40px;
    text-align: right;
    padding-right: 12px;
    margin-top: 8px;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    font-weight: 700;
    white-space: nowrap;
  }
  .specifications-content {
    flex: 1;
    border-radius: 6px;
    background-color: rgba(250, 250, 250, 1);
    border: 1px solid rgba(255, 0, 0, 0);
  }
}
.el-table /deep/ .has-gutter {
  background-color: rgba(250, 250, 250, 1);
}
.el-table /deep/ .myUpload {
  .img-wrapper {
    .filter {
      .el-icon-delete,
      .el-icon-zoom-in {
        font-size: 20px !important;
      }
      .el-icon-zoom-in {
        margin-right: 5px !important;
      }
    }
  }
}
.el-row {
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.check /deep/ .el-form-item__label {
  width: auto !important;
}
.check /deep/ .el-form-item__content {
  margin-left: 0 !important;
}
</style>
